<template>
  <div class="oe-add-exam" v-loading="loading">
    <top-tip v-if="!stepMode && (batchTitle || $route.name === 'addExam')" :examTitle="examTitle" :batchTitle="batchTitle"></top-tip>
    <div class="oe-add-exam__content">
      <div class="oe-content-container">
        <p class="oe-add-exam__title">考试名称</p>
        <a-form :form="form" @submit="handleSubmit">
          <a-form-item label="名称：" :label-col="{ span: 5 }" :wrapper-col="{ span: 18 }">
            <a-input
              :disabled="onlyRead"
              v-decorator="['name', { rules: [{ required: true, message: '请输入考试名称！' }] }]"
              placeholder="输入考试名称"
            />
          </a-form-item>
          <a-form-item label="考试总分：" :label-col="{ span: 5 }" :wrapper-col="{ span: 18 }">
            <a-input-number
              :disabled="onlyRead"
              v-decorator="['score', { initialValue: 100, rules: [{ required: true, message: '请输入考试总分！' }] }]"
              placeholder="输入考试总分"
              :min="1"
              defaultValue="100"
              style="width: 100%;"
            />
          </a-form-item>
          <a-form-item label="考试分类：" :label-col="{ span: 5 }" :wrapper-col="{ span: 18 }">
            <a-select
              :disabled="onlyRead"
              v-decorator="['examType']"
              placeholder="选择考试分类"
              @change="handleExamChange"
              showSearch
              optionFilterProp="children"
              @search="handleExamSearch"
              allowClear
              :notFoundContent="fetching ? undefined : '无数据'"
            >
              <a-spin v-if="fetching" slot="notFoundContent" size="small" />
              <a-select-option :value="item.id" v-for="item in examTypeList" :key="item.id">
                {{ item.text }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="设置题目负责人：" :label-col="{ span: 5 }" :wrapper-col="{ span: 18 }">
            <a-select
              :disabled="onlyRead"
              v-decorator="['teacher', { rules: [{ required: true, message: '请选择设置题目负责人！' }] }]"
              placeholder="选择设置题目负责人"
              @change="handleTeacherChange"
              showSearch
              optionFilterProp="children"
              @search="handleTeacherSearch"
              allowClear
              :notFoundContent="fetching ? undefined : '无数据'"
            >
              <a-spin v-if="fetching" slot="notFoundContent" size="small" />
              <a-select-option :value="item.id" v-for="item in teacherList" :key="item.id">
                {{ item.text }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item v-if="examMode == 2" label="考试方式：" :label-col="{ span: 5 }" :wrapper-col="{ span: 18 }">
            <a-radio-group v-model="radioGroup" @change="$parent.onChangeExamMode" :disabled="onlyRead">
              <a-radio :value="0">
                线上考试
              </a-radio>
              <a-radio :value="1">
                线下考试
              </a-radio>
            </a-radio-group>
            <span class="span-tips"
              >注：线上考试学生打开网站或APP，输入信息就可以考试；线下考试需要设置考场，在教师机学生机下载本考场专属客户端进行考试</span
            >
          </a-form-item>
          <a-form-item label="是否需要审核" :label-col="{ span: 5 }" :wrapper-col="{ span: 18 }">
            <a-radio-group v-model="isNeedCheck" :disabled="onlyRead">
              <a-radio :value="0">
                否
              </a-radio>
              <a-radio :value="1">
                是
              </a-radio>
            </a-radio-group>
            <!--  -->
            <span class="span-tips" v-if="sysType == 2">注：若勾选审核，设置题目后需要按照教师顺序进行审核，审核通过后才能进行试卷打印或导出。</span>
            <span class="span-tips" v-else>注：若勾选审核，发布考试后需要按照教师顺序进行审核，审核通过后学生才能进行作答。</span>
          </a-form-item>
          <!-- <a-form-item label="审核人" :label-col="{ span: 5 }" :wrapper-col="{ span: 18 }" v-if="isNeedCheck == 1">
            <div v-for="(audit,num) in auditList" :key="num" style="width: 50%;display: inline-block;margin: 0px 5px 10px 0px;">
              {{num+1}}.
              <a-select
                class="audit-select"
                v-decorator="['audit', { rules: [{ required: true, message: '请选择审核人！' }] }]"
                placeholder="选择审核人"
                @change="handleauditListChange"
                v-model="auditList[num]"
                showSearch
                optionFilterProp="children"
                @search="handleauditListSearch"
                allowClear
                :notFoundContent="fetching ? undefined : '无数据'"
              >
                <a-spin v-if="fetching" slot="notFoundContent" size="small" />
                <a-select-option :value="num+':'+item.id" v-for="item in teacherList" :key="num+':'+item.id">
                  {{ item.text }}
                </a-select-option>
              </a-select>
              <i class="iconfont audit-btn1 icon-plus-circle" @click="addAudit(num)"></i>
              <i class="iconfont audit-btn2 icon-delete" @click="deleteAudit(num)"></i>
              <span>-></span>
            </div>
          </a-form-item> -->
          <div class="form-item-box" v-show="isNeedCheck == 1">
            <div class="form-item-label">审核人：</div>
            <div class="from-item-content">
              <div v-for="(audit,num) in auditList" :key="num" style="width: calc(50% - 10px);display: inline-block;margin: 0px 5px 10px 0px;">
                <span class="audit-item-num">{{`第${num_zh[num]}审核人:`}}</span>
                <a-select
                  :disabled="onlyRead"
                  class="audit-select"
                  placeholder="选择审核人"
                  @change="handleauditListChange()"
                  v-model="auditList[num]"
                  showSearch
                  optionFilterProp="children"
                  @search="handleauditListSearch"
                  allowClear
                  :notFoundContent="fetching ? undefined : '无数据'"
                >
                  <a-select-option :value="item.id" v-for="item in auditTeacherList" :key="item.id">
                    {{ item.text }}
                  </a-select-option>
                </a-select>
                <i v-if="!onlyRead" class="iconfont audit-btn2 icon-delete" @click="deleteAudit(num)"></i>
                <i v-if="!onlyRead" class="iconfont audit-btn1 icon-plus-circle" @click="addAudit(num)"></i>
                <span v-if="num+1 < auditList.length" style="margin: 0px 5px 0px 10px;">-></span>
              </div>
            </div>
          </div>
          <a-form-item :label="'要求：(字数：'+requirement.length+'/220)'" :label-col="{ span: 5 }" :wrapper-col="{ span: 18 }">
            <a-input :disabled="onlyRead" type="textarea" maxLength="220" @pressEnter="checkEnter(event)" :rows="4" v-model="requirement" v-decorator="['requirement']" placeholder="输入考试要求" />
          </a-form-item>
          <a-form-item class="oe-addexam-btn" v-if="!stepMode">
            <a-button type="primary" @click.stop="saveExam">
              确认
            </a-button>
            <a-button @click.stop="$router.back()">
              取消
            </a-button>
          </a-form-item>
          <a-form-item class="oe-addexam-btn" v-else>
            <a-button v-if="!onlyRead" type="primary" @click="stepSave">
              保存
            </a-button>
            <a-button v-if="!onlyRead" type="primary" @click="stepSave('next')">
              保存并下一步
            </a-button>
            <a-button v-if="examid && onlyRead" type="primary" @click="$parent.nextStep()">
              下一步
            </a-button>
          </a-form-item>
        </a-form>
        <a-modal
          class="oe-add-modal"
          title="提示"
          centered="true"
          :closable="false"
          :maskClosable="false"
          :visible="visible"
          @ok="handleOk"
          @cancel="handleCancel"
          okText="是"
          cancelText="否"
        >
          <p class="oe-add-exam__text">{{ ModalText }}</p>
        </a-modal>
      </div>
    </div>
  </div>
</template>

<script>
import topTip from '@/components/top-tip/index.vue';
export default {
  name: 'addExam',
  components: {
    topTip
  },
  props:{
    stepMode:{
      type:Boolean,
      default:false
    },
    examid:{
      type:String,
      default:''
    },
    batchid:{
      type:String,
      default:''
    },
    onlyRead:{
      type:Boolean,
      default:false
    },
    sysType: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      form: this.$form.createForm(this),
      loading: false,
      radioGroup: 0,
      ExamMode: 0,
      isNeedCheck: 0,
      // 分类列表
      examTypeList: [],
      // 教师列表
      teacherList: [],
      auditTeacherList: [],
      requirement: '',
      fetching: false,
      visible: false,
      ModalText: '',
      isTestPaper: null,
      examMode: 2,
      // 审核人
      auditList: [undefined],
      batchTitle:'',
      examTitle:'',
      num_zh:{
        0:'一',
        1:'二',
        2:'三',
        3:'四',
        4:'五',
        5:'六',
        6:'七',
        7:'八',
        8:'九',
        9:'十',
      }
    };
  },
  mounted() {
    this.getBatchList();
    let id = this.examid;
    if (id && this.$route.name == 'editExam') {
      this.getExamInfo();
    }
    if(this.stepMode && this.examid){
      this.getExamInfo();
    }
    if(this.$route.name == 'addExam'){
      this.getExamList();
    }
    this.getTeacherList();
    this.getAuditTeacherList();
  },
  methods: {
    checkEnter(e){
      var et=e||window.event;
      var keycode=et.charCode||et.keyCode;
      if (keycode==13) {
        if (window.event) {
          window.event.returnValue = false;
        } else {
          e.preventDefault();//for firefox
        }
      }
    },
    handleExamSearch(val) {
      this.getBatchList(val);
    },
    handleTeacherSearch(val) {
      this.getTeacherList(val);
    },
    handleauditListSearch(val) {
       this.getAuditTeacherList(val);
    },
    // 获取分类列表
    getBatchList(val) {
      this.fetching = true;
      this.$http
        .post('/api/design/workexam/getBatch', {
          q: val ? val : '',
          batchid : this.batchid
        })
        .then((rst) => {
          this.fetching = false;
          this.examTypeList = [];
          if (rst.code == 1) {
            this.examMode = rst.examMode;
            this.stepMode && this.$parent.initStep(rst.examMode)
            this.examTypeList = rst.list;
          } else {
            this.$messasge.error(rst.msg);
          }
        });
    },
    // 获取教师列表
    getTeacherList(val) {
      this.fetching = true;
      this.$http
        .post('/api/design/workexam/getDutyTea', {
          q: val ? val : ''
        })
        .then((rst) => {
          this.fetching = false;
          this.teacherList = [];
          if (rst.code == 1) {
            this.teacherList = rst.list;
          } else {
            this.$messasge.error(rst.msg);
          }
        });
    },
    getAuditTeacherList(val) {
      this.fetching = true;
      this.$http
        .post('/api/design/workexam/getDutyTea', {
          q: val ? val : ''
        })
        .then((rst) => {
          this.fetching = false;
          this.auditTeacherList = [];
          if (rst.code == 1) {
            this.auditTeacherList = rst.list;
          } else {
            this.$messasge.error(rst.msg);
          }
        });
    },
    stepSave(next){
      this.form.validateFields((err, values) => {
        if (!err) {
          this.visible = true;
          const userId = localStorage.getItem('userId');
            this.visible = false;
            this.isTestPaper = false;
            this.add1 = true
            this.handleSubmit(next);
        } else {
          this.$message.error('请把数据填写完整');
        }
      });
    },
    getExamList() {
      this.loading = true;
      this.$http
        .post('/api/design/workexam/getExamList', {
          batchId: this.batchid,
        })
        .then((rst) => {
          this.loading = false;
          if (rst.code == 1) {
            this.batchTitle = rst.batchTitle;
          } else {
            this.$message.error(rst.msg);
          }
        });
    },
    saveExam() {
      this.form.validateFields((err, values) => {
        if (!err) {
          this.visible = true;
          const userId = localStorage.getItem('userId');
          if (values.teacher === userId) {
            this.visible = true;
            this.ModalText = '是否前往组卷？';
          } else {
            this.visible = false;
            this.isTestPaper = false;
            this.handleSubmit();
            this.ModalText = '是否通知责任老师组卷？';
          }
        } else {
          this.$message.error('请把数据填写完整');
        }
      });
    },
    // 保存或编辑试卷
    handleSubmit(next) {
      // e.preventDefault();
      var _this = this;
      this.loading = true;
      let examid = _this.examid ? _this.examid : '';
      let batchid = _this.batchid ? _this.batchid : '';
      var examMode = _this.radioGroup;
      if(this.examMode == 0 || this.examMode == 1){
        examMode = this.examMode;
      }
      this.form.validateFields((err, values) => {
        if (!err) {
          _this.$http
            .post('/api/design/workexam/saveExam', {
              examId: examid,
              title: values.name,
              score: values.score,
              sortId: values.examType,
              teacherId: values.teacher,
              batchId: batchid,
              remark: values.requirement,
              examMode: examMode,
              isNeedCheck: _this.isNeedCheck,
              checkerIds:this.auditList
            })
            .then((rst) => {
              this.loading = false;
              if (rst.code == 1) { 
                if (examid) {
                  this.$message.success('编辑成功!');
                } else {
                  this.$message.success('新增成功!');
                }
                if (this.isTestPaper) {
                  this.$router.replace({
                    name: 'testPaper',
                    params: {
                      examid: rst.examId
                    }
                  });
                } else {
                  if(this.stepMode){
                    this.$store.commit('setExamId',rst.examId)
                    if(next === 'next'){
                      this.$parent.getExamInfo(next)
                    }else{
                      this.$parent.getExamInfo()
                    }
                  }else{
                    this.$router.back();
                  }
                }
              } else {
                this.$message.error(rst.msg);
                if(next === 'next'){
                  this.$parent.getExamInfo(next)
                }
              }
            });
        } else {
          this.$message.error('请把数据填写完整');
        }
      });
    },
    // 获取考试信息
    getExamInfo() {
      this.loading = true;
      this.$http
        .post('/api/design/workexam/getExamInfo', {
          id: this.examid
        })
        .then((rst) => {
          this.loading = false;
          if (rst.code == 1) {
            this.form.setFieldsValue({
              examType: rst.info.SortId,
              name: rst.info.Title,
              score: rst.info.TotalScore,
              teacher: rst.info.TeacherId,
              requirement: rst.info.Remark
            });
            this.auditList = rst.teaIdList.length>0?rst.teaIdList:[undefined];
            this.requirement = rst.info.Remark;
            this.radioGroup = rst.info.ExamMode;
            this.ExamMode = rst.info.ExamMode;
            // this.$parent.getExamStatus(rst.info.ExamMode)
            this.isNeedCheck = rst.info.IsNeedCheck
            this.examTitle = rst.info.Title
          } else {
            this.$message.error(rst.msg);
          }
        });
    },
    handleExamChange(value) {
      this.form.setFieldsValue({
        examType: value
      });
    },
    handleOk(e) {
      this.visible = false;
      this.isTestPaper = true;
      this.handleSubmit();
    },
    handleCancel(e) {
      this.visible = false;
      this.isTestPaper = false;
      this.handleSubmit();
    },
    handleTeacherChange(val) {
      this.form.setFieldsValue({
        teacher: val
      });
    },
    handleauditListChange() {
      this.getAuditTeacherList('');
    },
    addAudit(num) {
      if (this.auditList.length < 10) {
        this.auditList.splice(num+1, 0, undefined)
      } else {
        this.$message.warning('最多10个审核人');
      }
    },
    deleteAudit(num) {
      if(this.auditList.length === 1){
        this.$message.warn('至少需要一个审核人')
        return
      }
      this.auditList.splice(num, 1)
    }
  }
};
</script>
